from google.appengine.ext import db
from google.appengine.tools import bulkloader

# NOTE:
# Use import-csv.py instead of this.  That way I can do a proper save,
# which builds the search index properly,
# and also make component imports possible by looking up the materials by name.

# TODO
# - Components.  Export them by name not id so we can import anywhere.
# - is_accord isn't imported.
# - Find how to import the djangoappengine models derived from the django models
#   instead of writing my own inventory_material.
# - Maybe that will also fix the missing search index.  Otherwise need a
#   separate import for that table?  ick.  have to save each material by hand in
#   order to build it in the first place.

# First some setup stolen from djangoappengine/main/main.py to set up the
# environment and paths.
import sys, os

parent_dir = os.path.abspath('common-apps')
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

# Remove the standard version of Django
if 'django' in sys.modules and sys.modules['django'].VERSION < (1, 2):
    for k in [k for k in sys.modules
              if k.startswith('django\.') or k == 'django']:
        del sys.modules[k]

# Do we need the boot stuff just to import the models?
from djangoappengine import boot
boot.setup_threading()
boot.setup_project()
boot.setup_logging()


# FIXME this borks because appengine looks for an implementation of its
# db.models, and this django stuff is a different class.  Maybe I can write some
# kind of bridge.  sigh.
# Or what if I just write a db.models file that I think will be compatible.  a
# bit dangerous, maybe?  I can look in the datastore viewer and see what the
# model is like, it's pretty straightforward port of inventory.models.
#from inventory.models import Material

from models_appengine_port import inventory_material

def float_or_none(val):
  if val:
    return float(val)
  return None

def int_or_none(val):
  if val:
    return int(val)
  return None

class MaterialLoader(bulkloader.Loader):
  def __init__(self):
    bulkloader.Loader.__init__(self, 'inventory_material',
                               [('name', str),
                                ('bottle_num', int_or_none),
                                ('notes', str),
                                ('ml_on_hand', int_or_none),
                                ('substantivity', int_or_none),
                                ('price_ml', float_or_none),
                               ])

loaders = [MaterialLoader]
